<template>
  <div class="good-operation">
    <el-collapse class="search-block" style="width: 1260px">
      <el-collapse-item title="条件搜索">
        <!-- 产品编号，产品名，开始到结束日期，添加区间 -->
        <el-form
          ref="searchGoodForm"
          :model="searchGoodForm"
          label-position="top"
        >
          <el-form-item class="search-item" label="产品编号" prop="goodId">
            <el-input
              type="text"
              v-model="searchGoodForm.goodId"
              style="width: 200px"
              placeholder="请输入产品编号"
            />
          </el-form-item>
          <el-form-item class="search-item" label="产品名" prop="goodTitle">
            <el-input
              type="text"
              v-model="searchGoodForm.goodTitle"
              style="width: 200px"
              placeholder="请输入产品名"
              maxlength="10"
            />
          </el-form-item>

          <el-form-item class="search-item" label="产品价格区间">
            <el-form-item prop="firstPrices" class="search-item">
              <el-input
                type="text"
                v-model="searchGoodForm.firstPrices"
                style="width: 200px"
                placeholder="请输入产品初始价"
              />
            </el-form-item>
            至
            <el-form-item
              prop="secPrices"
              class="search-item"
              style="margin-left: 0px"
            >
              <el-input
                type="text"
                v-model="searchGoodForm.secPrices"
                style="width: 200px"
                placeholder="请输入产品截至价"
              />
            </el-form-item>
          </el-form-item>

          <el-form-item label="秒杀时间" class="search-item" prop="seckillTime">
            <div class="block">
              <el-date-picker
                v-model="searchGoodForm.seckillTime"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="添加时间" class="search-item" prop="createTime">
            <div class="block">
              <el-date-picker
                v-model="searchGoodForm.createTime"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <div class="search-button" style="margin-top: 100px">
            <el-button
              type="warning"
              icon="el-icon-search"
              @click="getGoodTableList()"
              >搜 索</el-button
            >
            <el-button
              icon="el-icon-delete"
              @click="resetForm('searchGoodForm')"
              >重 置</el-button
            >
          </div>
        </el-form>
      </el-collapse-item>
    </el-collapse>

    <div class="good-table">
      <el-table :data="goodTableList" stripe v-loading="goodTableLoading">
        <el-table-column
          prop="good_id"
          label="产品编号"
          align="center"
          width="100px"
        />
        <el-table-column
          prop="good_title"
          label="产品名"
          align="center"
          width="100px"
        />
        <el-table-column
          prop="price"
          label="产品价格/元"
          align="center"
          width="120px"
        />
        <el-table-column
          prop="seckill_price"
          label="秒杀价格"
          align="center"
          width="120px"
        />
        <el-table-column
          prop="total"
          label="总量"
          align="center"
          width="80px"
        />
        <el-table-column
          prop="remain"
          label="剩余数量"
          align="center"
          width="80px"
        />
        <el-table-column
          prop="start_time"
          label="开始时间"
          align="center"
          width="160px"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.start_time | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="end_time"
          label="结束时间"
          align="center"
          width="160px"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.end_time | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="添加时间"
          align="center"
          width="160px"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.create_time | dateFormat("yyyy-mm-dd hh:mm:ss")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="openEditGoodDialog(scope.row.good_id)"
              >编辑</el-button
            >
            <el-button type="danger" @click="deleteGood(scope.row.good_id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getGoodTableList"
      />
    </div>

    <div class="edit-good-dialog">
      <!-- 订单详情窗口 -->
      <el-dialog title="编辑产品" width="464px" :visible.sync="editGoodDialog">
        <el-form
          ref="editGoodForm"
          :model="editGoodForm"
          :rules="editGoodRules"
          label-position="top"
        >
          <!-- 产品图片、产品名、产品价格、产品秒杀价、产品总量、产品描述、开始时间、结束时间 -->
          <div class="upload-image">
            <el-form-item label="产品图片" prop="good_img">
              <el-image v-loading="uploadLoading" :src="editGoodForm.good_img">
              </el-image>
              <el-upload
                style="display: inline-block"
                :action="uploadUrl"
                list-type="picture"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                :headers="headers"
                :on-error="handleUploadError"
                :show-file-list="false"
                name="file"
              >
                <el-button type="primary">修改图片</el-button>
              </el-upload>
            </el-form-item>
          </div>

          <div class="edit-good-title">
            <el-form-item label="产品名" prop="good_title">
              <el-input
                type="text"
                maxlength="10"
                placeholder="请输入产品名"
                v-model="editGoodForm.good_title"
              />
            </el-form-item>
          </div>

          <div class="edit-good-prices">
            <el-form-item label="产品价格" prop="price">
              <el-input
                type="text"
                placeholder="请输入产品价格"
                v-model="editGoodForm.price"
              />
            </el-form-item>
          </div>

          <div class="edit-good-seckill-prices">
            <el-form-item label="秒杀价格" prop="seckill_price">
              <el-input
                type="text"
                placeholder="请输入秒杀价格"
                v-model="editGoodForm.seckill_price"
              />
            </el-form-item>
          </div>

          <div class="edit-good-total">
            <el-form-item label="产品总量" prop="total">
              <el-input
                type="text"
                placeholder="请输入产品总量"
                v-model="editGoodForm.total"
              />
            </el-form-item>
          </div>

          <div class="edit-good-desc">
            <el-form-item label="产品描述" prop="good_desc">
              <el-input
                type="textarea"
                maxlength="100"
                placeholder="请输入产品描述(小于100字)"
                v-model="editGoodForm.good_desc"
              />
            </el-form-item>
          </div>

          <div class="edit-start-time">
            <el-form-item label="开始时间" prop="start_time">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="editGoodForm.start_time"
                  style="width: 100%"
                ></el-date-picker>
              </el-col>
              <el-col :span="11" style="margin-left: 5%">
                <el-time-picker
                  placeholder="选择时间"
                  v-model="editGoodForm.start_time"
                  style="width: 100%"
                ></el-time-picker>
              </el-col>
            </el-form-item>
          </div>

          <div class="edit-end-time">
            <el-form-item label="结束时间" prop="end_time">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="editGoodForm.end_time"
                  style="width: 100%"
                ></el-date-picker>
              </el-col>
              <el-col :span="11" style="margin-left: 5%">
                <el-time-picker
                  placeholder="选择时间"
                  v-model="editGoodForm.end_time"
                  style="width: 100%"
                ></el-time-picker>
              </el-col>
            </el-form-item>
          </div>

          <div class="edit-button">
            <el-button
              type="primary"
              :loading="editGoodLoading"
              @click="editGood()"
            >
              <span v-if="!editGoodLoading">修 改</span>
              <span v-else>修 改 中...</span>
            </el-button>
          </div>

          <div class="reset-button">
            <el-button @click="resetForm('editGoodForm')">重置</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getGoodList, getGood, modifyGood, deleteGood } from "@/api/good";
import { getToken } from "@/utils/auth";
export default {
  name: "GoodOperation",
  data() {
    var checkPrice = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("价格不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        }
      }, 1000);
    };
    var checkTotal = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("产品总量不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        }
      }, 1000);
    };
    return {
      searchGoodForm: {
        goodId: "",
        goodTitle: "",
        firstPrices: "",
        secPrices: "",
        seckillTime: "",
        createTime: "",
      },

      queryParams: {
        pageNum: 1,
        pageSize: 5,
        goodId: "",
        goodTitle: "",
        firstPrices: "",
        secPrices: "",
        startDate: "",
        endDate: "",
        firstCreatTime: "",
        secCreateTime: "",
      },
      total: 0,

      goodTableList: [],
      goodTableLoading: false,
      editGoodDialog: false,
      editGoodLoading: false,

      editGoodForm: {
        good_img: "",
        good_title: "",
        price: "",
        seckill_price: "",
        total: "",
        good_desc: "",
        start_time: "",
        end_time: "",
      },
      editGoodRules: {
        goodTitle: [
          {
            required: true,
            message: "产品名不能为空",
            trigger: "blur",
          },
        ],
        goodPrices: [
          {
            validator: checkPrice,
            trigger: "blur",
          },
        ],
        seckillPrices: [
          {
            validator: checkPrice,
            trigger: "blur",
          },
        ],
        total: [
          {
            validator: checkTotal,
            trigger: "blur",
          },
        ],
        goodDesc: [
          {
            required: true,
            message: "产品描述不能为空",
            trigger: "blur",
          },
        ],
        start_time: [
          {
            required: true,
            message: "请输入开始时间不能为空",
            trigger: "blur",
          },
        ],
        end_time: [
          {
            required: true,
            message: "请输入结束时间不能为空",
            trigger: "blur",
          },
        ],
      },
      uploadLoading: false,

      uploadUrl: "/api/file/upload",
      headers: {
        tokenAuthorization: "Bearer" + getToken(),
      },
    };
  },
  created() {
    this.getGoodTableList();
  },
  methods: {
    getGoodTableList() {
      this.packParams();
      this.goodTableLoading = true;
      getGoodList(this.queryParams)
        .then((res) => {
          this.goodTableList = res.rows;
          this.total = res.total;
          this.goodTableLoading = false;
        })
        .catch((err) => {
          this.goodTableLoading = false;
        });
    },
    packParams() {
      let form = this.searchGoodForm;
      if (form.goodId != null && form.goodId != "") {
        if (isNaN(form.goodId)) {
          this.$message.error("产品编号是数字");
          return;
        }
      }
      if (form.firstPrices != null && form.firstPrices != "") {
        if (isNaN(form.firstPrices)) {
          this.$message.error("价格是数字");
          return;
        }
      }
      if (form.secPrices != null && form.secPrices != "") {
        if (isNaN(form.secPrices)) {
          this.$message.error("价格是数字");
          return;
        }
      }
      this.queryParams.goodId = form.goodId;
      this.queryParams.goodTitle = form.goodTitle;
      this.queryParams.firstPrices = form.firstPrices;
      this.queryParams.secPrices = form.secPrices;
      this.queryParams.startDate =
        form.seckillTime === null ? null : form.seckillTime[0];
      this.queryParams.endDate =
        form.seckillTime === null ? null : form.seckillTime[1];
      this.queryParams.firstCreatTime =
        form.createTime === null ? null : form.createTime[0];
      this.queryParams.secCreateTime =
        form.createTime === null ? null : form.createTime[1];
    },
    openEditGoodDialog(goodId) {
      getGood(goodId).then((res) => {
        this.editGoodForm = res.data;
        if (new Date(this.editGoodForm.start_time) - new Date() <= 86400000) {
          this.$confirm("该产品在秒杀前一天或秒杀已结束，无法修改", "注意", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error",
          })
            .then(() => {
              this.editGoodForm = null;
              this.editGoodDialog = false;
              return false;
            })
            .catch(() => {});
        } else this.editGoodDialog = true;
      });
    },
    editGood() {
      this.editGoodLoading = true;
      modifyGood(this.editGoodForm)
        .then((res) => {
          this.$message.success("修改成功!");
          this.editGoodLoading = false;
          this.editGoodDialog = false;
          this.getGoodTableList();
        })
        .catch((err) => {
          this.editGoodLoading = false;
        });
    },
    deleteGood(goodId) {
      this.$confirm("确定要删除该产品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteGood(goodId).then((res) => {
            this.$message.success("删除成功");
            this.getGoodTableList();
          });
        })
        .catch(() => {});
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleUploadSuccess(res) {
      this.$message.success("上传成功！");
      this.editGoodForm.good_img = res.data.url;
      this.uploadLoading = false;
    },

    handleBeforeUpload(file) {
      let fileExtension = "";
      if (file.name.lastIndexOf(".") > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      }

      if (
        fileExtension != "jpg" &&
        fileExtension != "png" &&
        fileExtension != "jpeg"
      ) {
        this.$message.error("上传图片格式不符");
        return false;
      }

      const fileSize = file.size / 1024 / 1024 < 5;
      if (!fileSize) {
        this.$message.error("上传图片大小不能超过 5MB！");
        return false;
      }

      this.uploadLoading = true;
    },

    handleUploadError() {
      this.$message.error("上传失败，请稍后重试");
      this.uploadLoading = false;
    },
  },

  filters: {
    dateFormat: function (val, args) {
      var time = new Date(val);
      var year = time.getFullYear();
      var month = time.getMonth() + 1;
      var day = time.getDate();

      if (month < 10) month = "0" + month;
      if (day < 10) day = "0" + day;

      if (args.toLowerCase() === "yyyy-mm-dd") {
        return year + "年" + month + "月" + day + "日";
      } else {
        var hour = time.getHours();
        var min = time.getMinutes();
        var sec = time.getSeconds();

        if (hour < 10) hour = "0" + hour;
        if (min < 10) min = "0" + min;
        if (sec < 10) sec = "0" + sec;

        return (
          year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec
        );
      }
    },
  },
};
</script>

<style>
.search-block {
  margin-bottom: 20px;
}

.el-collapse-item__header {
  color: #4091ff !important;
  font-size: 15px;
}

.search-item {
  display: inline-block;
  margin-left: 20px;
}

.el-form-item__label {
  padding-bottom: 0px !important;
}

.search-button {
  float: right;
  margin-bottom: 20px;
}

.image-uploade .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-left: 30px;
  margin-top: 10px;
}
.image-uploade .el-upload:hover {
  border-color: #409eff;
}
.image-uploade-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.image {
  width: 200px;
  height: 100px;
  display: block;
}

.el-form-item__label {
  padding-bottom: 0px !important;
}

.edit-button,
.reset-button {
  display: inline-block;
  margin-left: 8%;
}

.edit-button .el-button,
.reset-button .el-button {
  width: 150px;
  height: 40px;
}
</style>